﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;

namespace Luminal
{
    public static class ObjectTracker
    {
        static Dictionary<IntPtr, LuminalObject> objects = new Dictionary<IntPtr, LuminalObject>();

        public static IEnumerable<LuminalObject> Objects
        {
            get { return objects.Values; }
        }

        static ObjectTracker()
        {
            AppDomain.CurrentDomain.ProcessExit += new EventHandler((sender, e) =>
            {
                LuminalObject[] remainingObjects = objects.Values.ToArray();
                foreach (LuminalObject obj in remainingObjects)
                    if (!obj.Disposed) obj.Dispose();
            });
        }

        internal static void RegisterObject(LuminalObject obj)
        {
            objects.Add(obj.InternalPointer, obj);
        }

        internal static void UnregisterObject(LuminalObject obj)
        {
            objects.Remove(obj.InternalPointer);
        }

        public static T GetObject<T>(IntPtr ptr) where T : LuminalObject
        {
            if (!objects.ContainsKey(ptr))
                throw new KeyNotFoundException("No object exists for the specified pointer.");

            LuminalObject output = objects[ptr];

            if (output is T)
                return output as T;
            else
                throw new Exception(string.Format("The object for the specified pointer is not of type {0}", typeof(T)));
        }

        public static bool ContainsObject(IntPtr ptr)
        {
            return objects.ContainsKey(ptr);
        }
    }
}
